import CryptoJS from 'crypto-js';
import api from '../api/api';
//import store from "../store/index"
import { resData } from './common';
//import store from "../store";
const util = {
    //加密
    encrypt(word, keyStr) {
        if (keyStr.length > 15) {
            let key = CryptoJS.enc.Utf8.parse(keyStr),
                srcs = CryptoJS.enc.Utf8.parse(word),
                iv = CryptoJS.enc.Utf8.parse('M2UsytYCU4FD70y5');

            let encrypted = CryptoJS.AES.encrypt(srcs,
                key,
                {mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, iv: iv});
            return encrypted.toString();
        } else {
            return "密钥长度必须大于15位";
        }

    },
    //解密
    decrypt(word, keyStr) {
        let key = CryptoJS.enc.Utf8.parse(keyStr),
            iv = CryptoJS.enc.Utf8.parse('M2UsytYCU4FD70y5');
        let decrypt = CryptoJS.AES.decrypt(word,
            key,
            {mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, iv: iv});
        return CryptoJS.enc.Utf8.stringify(decrypt).toString();
    },
    encodeUrl(data) {
        try {
            let tempArr = [];
            for (let i in data) {
                let key = encodeURIComponent(i);
                let value = encodeURIComponent(data[i]);
                tempArr.push(key + '=' + value);
            }
            return tempArr.join('&');
        } catch (err) {
            return '';
        }
    },
    /*自定义翻译*/
    dictTranslate(arr, status) {
        let dictName = "";
        for(let i=0; i<arr.length; i++) {
            if(status == arr[i].value) {
                dictName = arr[i].name;
                break
            }
        }
        return dictName
    },
    //记录滚动的位置
    /*
    pageXOffset 和 pageYOffset 属性返回文档在窗口左上角水平和垂直方向滚动的像素。

    pageXOffset 设置或返回当前页面相对于窗口显示区左上角的 X 位置。pageYOffset 设置或返回当前页面相对于窗口显示区左上角的 Y 位置。

    pageXOffset 和 pageYOffset 属性相等于 scrollX 和 scrollY 属性。
     */
    getScrollTop() {
        let supportPageOffset = window.pageXOffset !== undefined;
        //document.compatMode : 标准兼容模式开启。
        let isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");

        let y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;
        //store.commit("saveScrollTop",window.document.documentElement.scrollTop);
        return y
    },
    setScrollTop() {
        //let y=document.documentElement.scrollTop = store.state.scrollTop;
        //return y
    },
    //获取动态密钥
    getDynamicSecretKey() {
        return new Promise((resolve, reject) => {
            api.getDynamicSecretKey().then(res => {
                let result = resData(res);
                resolve(result)
            }).catch(() => {
                reject(null)
            })
        })
    },
    /*
    * 获取用户信息
    * 涉及购买等需要判断用户信息(vip, 绑定微信,绑定手机等)
    * */
    getUserInfo(store) {
        return new Promise((resolve, reject) => {
            api.getUserInfo("1").then(res => {
                let result = resData(res);
                if(result) {
                    store.commit('saveUserInfo', result);
                }
                resolve(result)
            }).catch((err) => {
                reject(err)
            })
        })
    },
    saveToken(data) {
        window.localStorage.setItem('Authorization',data.token);
        window.localStorage.setItem('AppId',data.userId);
    },
    //退出登录
    logoutSaveData(){
        window.localStorage.setItem('Authorization',"");
        window.localStorage.setItem('AppId',"");
    },
    //微信浏览器判断
    isWxBrowser() {
        let userAgent = window.navigator.userAgent.toLowerCase();
        return userAgent.match(/MicroMessenger/i) == "micromessenger"
    },
    //后端错误码判断,登录是否失效
    resCodeJudge(code) {
        let permission = false;
        let mesTip = "";
        if(code == "E000008" ) {
            permission = true;
            mesTip = "未登录"
        }
        if( code == "E000009" || code == "E000012" || code == "E000013" || code == "E000014") {
            permission = true;
            mesTip = "登录失效"
        }
        return {
            permission: permission,
            mesTip: mesTip
        }
    },
    //全局路由守卫函数
    routerBeforeFn(to, from, next, store) {
        if(to.meta) {
            if (to.meta.keepAlive) {
                store.commit('keepAliveSave', to.name)
            }
            store.commit('setTabBar', !!to.meta.tabBar)
        }

        //inviteNum会在多种场合出现，比如微信分享链接；扫商家二维码等等
        if(to.query.inviteNum) {
            store.commit('setInviteNum', to.query.inviteNum)
        }
        //receiveId 任务id
        if(to.query.receiveId) {
            store.commit('setReceiveId', to.query.receiveId)
        }
        // //-------------
        // let prePath = "";
        // //待优化，将参数带上
        // if(from.path === "/login" || from.path === "/register" || from.path === "/" || from.path === "/wxLogin" ) {
        //     prePath = "/index"
        // }else {
        //     //涉及到需要保存上一页数据的，可以拼接到地址
        //     prePath = from.fullPath
        // }
        // store.commit("setPrePath", prePath)
    },
    //金钱数字处理
    moneyFmt(moneyNum) {
        return Math.round(moneyNum * 1000) / 1000;
    },

};

export default util
